import { getOrgList, addOrg, updateOrg, deleteOrg, updateOrgStatus, getOrgDetail, getOrgTree, addUserToOrg, getOrgInvitationCode } from '@/api/org'
import { sendEmailCode } from '@/api/common'

export default {
  data() {
    return {
      loading: false,
      orgList: [],
      total: 0,
      searchForm: {
        org_id: '',
        org_level: '1' // 默认查看一级机构
      },
      // 机构表单
      orgDialogVisible: false,
      orgDialogTitle: '添加机构',
      orgForm: {
        orgId: null,
        parentId: null,
        orgName: '',
        orgType: 'SCHOOL',
        orgLevel: '1',
        contactPhone: '',
        address: '',
        email: '',
        status: 1,
        sortOrder: 0
      },
      orgRules: {
        orgName: [{ required: true, message: '请输入机构名称', trigger: 'blur' }],
        orgType: [{ required: true, message: '请选择机构类型', trigger: 'change' }],
        orgLevel: [{ required: true, message: '请选择机构层级', trigger: 'change' }],
        contactPhone: [
          { required: true, message: '请输入机构电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$/, message: '请输入正确的电话号码', trigger: 'blur' }
        ],
        address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入管理员邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        parentId: [
          {
            validator: (rule, value, callback) => {
              if (this.orgForm.orgLevel !== '1' && !value) {
                callback(new Error('非一级机构必须选择父级机构'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ]
      },
      // 机构类型选项
      orgTypeOptions: [
        { label: '学校', value: 'SCHOOL' },
        { label: '企业', value: 'COMPANY' },
        { label: '政府', value: 'GOVERNMENT' },
        { label: '其他', value: 'OTHER' }
      ],
      // 机构层级选项
      orgLevelOptions: [
        { label: '总部（学校）', value: '1' },
        { label: '分部（学院）', value: '2' },
        { label: '部门（班级/年级）', value: '3' }
      ],
      // 状态选项
      statusOptions: [
        { label: '启用', value: 1 },
        { label: '停用', value: 2 }
      ],
      // 父级机构选项
      parentOrgOptions: [],
      // 添加子机构场景控制
      isAddingChild: false,
      parentLevelForChild: null,
      parentOrgTypeForChild: null,
      // 详情弹窗（不再使用，仅保留字段避免侵入性改动）
      orgDetailDialogVisible: false,
      orgDetail: null,
      orgDetailActiveTab: 'summary',
      // 右侧详情面板
      orgDetailPanelVisible: false,
      // 机构树
      orgTreeLoading: false,
      orgTree: [],
      // 添加用户到机构
      addUserLoading: false,
      addUserForm: {
        userId: ''
      },
      addUserDialogVisible: false,
      // 邀请码生成
      invite: {
        codeToken: '',
        loading: false,
        code: '',
        sending: false
      },
      inviteDialogVisible: false,
      // Batch import users
      batchImport: {
        visible: false,
        uploading: false,
        file: null
      },
      // 基本信息编辑弹窗
      basicEditDialogVisible: false,
      basicEditForm: {
        orgId: '',
        orgName: '',
        contactPhone: '',
        address: ''
      },
      basicEditRules: {
        orgName: [{ required: true, message: '请输入机构名称', trigger: 'blur' }],
        contactPhone: [
          { required: true, message: '请输入机构电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$/, message: '请输入正确的电话号码', trigger: 'blur' }
        ],
        address: [{ required: true, message: '请输入地址', trigger: 'blur' }]
      }
    }
  },
  mounted() {
    this.getOrgList()
    this.loadParentOrgOptions()
  },
  methods: {
    // 打开添加用户对话框
    openAddUserDialog() {
      if (!this.orgDetail || !this.orgDetail.orgId) {
        this.$message.error('缺少机构上下文')
        return
      }
      this.addUserForm.userId = ''
      this.addUserDialogVisible = true
    },

    // 打开生成邀请码对话框
    openInviteDialog() {
      if (!this.orgDetail || !this.orgDetail.orgId) {
        this.$message.error('缺少机构上下文')
        return
      }
      this.invite = { codeToken: '', loading: false, code: '', sending: false }
      this.inviteDialogVisible = true
    },

    // 获取状态按钮类型
    getStatusButtonType(status) {
      switch (status) {
        case 1: return 'warning' // 启用 -> 停用
        case 2: return 'success' // 停用 -> 启用
        default: return 'warning'
      }
    },

    // 从机构树打开详情
    openOrgDetailFromTree(node) {
      const orgId = node && (node.orgId || node.id)
      if (!orgId) return
      // 复用查看接口并打开右侧面板
      this.viewOrgDetail({ orgId })
    },

    // 中文名称映射：机构类型
    getOrgTypeLabel(type) {
      const item = this.orgTypeOptions.find(o => o.value === type)
      return item ? item.label : type
    },

    // 中文名称映射：机构层级
    getOrgLevelLabel(level) {
      const item = this.orgLevelOptions.find(o => o.value === (typeof level === 'number' ? String(level) : level))
      return item ? item.label : level
    },

    // 状态中文
    getStatusText(status) {
      if (status === 1) return '启用'
      if (status === 2) return '停用'
      return '未知'
    },

    // 时间格式化
    formatDateTime(input) {
      if (!input) return '-'
      const d = new Date(input)
      if (!isNaN(d.getTime())) {
        const pad = n => (n < 10 ? '0' + n : String(n))
        const y = d.getFullYear()
        const m = pad(d.getMonth() + 1)
        const day = pad(d.getDate())
        const h = pad(d.getHours())
        const mi = pad(d.getMinutes())
        const s = pad(d.getSeconds())
        return `${y}-${m}-${day} ${h}:${mi}:${s}`
      }
      return String(input).replace('T', ' ')
    },

    // 获取状态按钮文本
    getStatusButtonText(status) {
      switch (status) {
        case 1: return '停用'
        case 2: return '启用'
        default: return '未知'
      }
    },

    // 获取机构类型标签类型
    getOrgTypeTagType(orgType) {
      switch (orgType) {
        case 'SCHOOL': return 'success'
        case 'COMPANY': return 'primary'
        case 'GOVERNMENT': return 'warning'
        case 'OTHER': return 'info'
        default: return 'info'
      }
    },

    // 获取机构类型标签文本
    getOrgTypeTagText(orgType) {
      const option = this.orgTypeOptions.find(item => item.value === orgType)
      return option ? option.label : orgType
    },

    // 获取机构层级标签类型
    getOrgLevelTagType(orgLevel) {
      switch (orgLevel) {
        case 1: return 'danger'
        case 2: return 'warning'
        case 3: return 'success'
        default: return 'info'
      }
    },

    // 获取机构层级标签文本
    getOrgLevelTagText(orgLevel) {
      const option = this.orgLevelOptions.find(item => item.value === orgLevel)
      return option ? option.label : `层级${orgLevel}`
    },

    // 获取机构列表
    async getOrgList() {
      this.loading = true
      try {
        const result = await getOrgList(this.searchForm)
        if (result && result.code === 1) {
          this.orgList = result.data || []
          this.total = this.orgList.length
        } else {
          this.$message.error(`获取机构列表失败: ${result?.msg || '未知错误'}`)
        }
      } catch (error) {
        this.$message.error(`获取机构列表异常: ${error.message}`)
      } finally {
        this.loading = false
      }
    },

    // 加载父级机构选项
    async loadParentOrgOptions() {
      try {
        // 获取所有机构用于选择父级机构
        const result = await getOrgList({ org_level: '1' })
        if (result && result.code === 1) {
          this.parentOrgOptions = result.data || []
        }
      } catch (error) {
        console.error('加载父级机构选项失败:', error)
      }
    },

    // 搜索
    handleSearch() {
      this.getOrgList()
    },

    // 重置
    handleReset() {
      this.searchForm = {
        org_id: '',
        org_level: '1'
      }
      this.getOrgList()
    },

    // 显示添加机构对话框
    showAddOrgDialog() {
      this.orgDialogTitle = '添加机构'
      this.isAddingChild = false
      this.parentLevelForChild = null
      this.parentOrgTypeForChild = null
      this.orgForm = {
        orgId: null,
        parentId: null,
        orgName: '',
        orgType: 'SCHOOL',
        orgLevel: '1',
        contactPhone: '',
        address: '',
        email: '',
        status: 1,
        sortOrder: 0
      }
      this.orgDialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.orgForm && this.$refs.orgForm.clearValidate) {
          this.$refs.orgForm.clearValidate()
        }
      })
    },

    // 编辑机构
    editOrg(row) {
      this.orgDialogTitle = '编辑机构'
      this.orgForm = {
        orgId: row.orgId,
        parentId: row.parentId,
        orgName: row.orgName,
        orgType: row.orgType,
        orgLevel: String(row.orgLevel),
        contactPhone: row.contactPhone || '',
        address: row.address || '',
        email: row.email || '',
        status: row.status,
        sortOrder: row.sortOrder || 0
      }
      this.orgDialogVisible = true
    },

    // 保存机构
    saveOrg() {
      if (!this.$refs.orgForm || !this.$refs.orgForm.validate) return
      this.$refs.orgForm.validate(async valid => {
        if (valid) {
          try {
            // 额外安全校验：添加子机构时机构类型必须与父级一致
            if (this.isAddingChild && this.parentOrgTypeForChild && this.orgForm.orgType !== this.parentOrgTypeForChild) {
              this.$message.error('子机构的机构类型必须与父级机构一致')
              return
            }
            if (this.orgForm.orgId) {
              // 编辑机构
              await updateOrg(this.orgForm)
              this.$message.success('机构更新成功')
            } else {
              // 添加机构 - 根据API文档构建请求数据
              const addData = {
                orgName: this.orgForm.orgName,
                orgType: this.orgForm.orgType,
                contactPhone: this.orgForm.contactPhone,
                address: this.orgForm.address,
                email: this.orgForm.email,
                orgLevel: this.orgForm.orgLevel
              }
              // 只有非一级机构才需要parentId
              if (this.orgForm.orgLevel !== '1' && this.orgForm.parentId) {
                addData.parentId = this.orgForm.parentId
              }
              const result = await addOrg(addData)
              if (result && result.code === 1) {
                this.$message.success('机构添加成功')
                // 显示管理员账号信息
                if (result.data && result.data.admin_userId && result.data.admin_password) {
                  this.$alert(
                    `管理员账号信息：\n用户名：${result.data.admin_userId}\n密码：${result.data.admin_password}`,
                    '添加成功',
                    {
                      confirmButtonText: '确定',
                      type: 'success'
                    }
                  )
                }
              } else {
                this.$message.error(`添加失败: ${result?.msg || '未知错误'}`)
              }
            }
            this.orgDialogVisible = false
            this.getOrgList()
            this.loadParentOrgOptions() // 重新加载父级机构选项
          } catch (error) {
            this.$message.error(`保存失败: ${error.message}`)
          }
        }
      })
    },

    // 切换状态
    async toggleStatus(row) {
      try {
        const newStatus = row.status === 1 ? 2 : 1
        await updateOrgStatus({ org_id: row.orgId, status: newStatus })
        this.$message.success('状态更新成功')
        this.getOrgList()
      } catch (error) {
        this.$message.error(`更新状态失败: ${error.message}`)
      }
    },

    // 删除机构
    deleteOrg(row) {
      if (!row) return
      const warnMsg = (row.orgLevel === 1 || row.orgLevel === 2)
        ? '删除一级或二级机构将会级联删除所有下属子机构，并移除其机构下所有用户，是否继续？'
        : '确定删除该机构吗？此操作不可恢复。'
      this.$confirm(warnMsg, '危险操作确认', {
        confirmButtonText: '我已知晓，继续删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false
      }).then(async() => {
        try {
          await deleteOrg({ org_id: row.orgId, org_level: row.orgLevel })
          this.$message.success('删除成功')
          this.getOrgList()
          this.loadParentOrgOptions() // 重新加载父级机构选项
        } catch (error) {
          this.$message.error(`删除失败: ${error.message}`)
        }
      }).catch(() => {})
    },

    // 查看子机构
    viewSubOrgs(row) {
      this.searchForm.org_id = row.orgId
      this.searchForm.org_level = String(row.orgLevel + 1)
      this.getOrgList()
    },

    // 跳转到该机构下的所有成员
    viewAllMembers(row) {
      if (!row || !row.orgId) return
      this.$router.push({
        path: '/form/user',
        query: { org_id: row.orgId }
      })
    },

    // 查看机构详情（改为打开右侧面板）
    async viewOrgDetail(row) {
      if (!row || !row.orgId) return
      try {
        this.loading = true
        const res = await getOrgDetail({ org_id: row.orgId })
        if (res && res.code === 1) {
          this.orgDetail = res.data || null
          this.orgDetailPanelVisible = true
          this.orgDetailDialogVisible = false
          this.orgDetailActiveTab = 'summary'
          // 加载机构树
          this.loadOrgTree(row.orgId)
          // 重置邀请码状态
          this.invite = { codeToken: '', loading: false, code: '', sending: false }
        } else {
          this.$message.error(`获取机构详情失败: ${res?.msg || '未知错误'}`)
        }
      } catch (error) {
        this.$message.error(`获取机构详情异常: ${error.message}`)
      } finally {
        this.loading = false
      }
    },

    // 打开右侧详情面板
    async openOrgDetailPanel(row) {
      if (!row || !row.orgId) return
      try {
        this.loading = true
        const res = await getOrgDetail({ org_id: row.orgId })
        if (res && res.code === 1) {
          this.orgDetail = res.data || null
          this.orgDetailPanelVisible = true
          // 同步加载机构树
          this.loadOrgTree(row.orgId)
          // 右侧面板重置邀请码状态
          this.invite = { codeToken: '', loading: false, code: '', sending: false }
        }
      } catch (e) {
        this.$message.error(`获取机构详情异常: ${e.message}`)
      } finally {
        this.loading = false
      }
    },

    // 关闭右侧详情面板
    closeOrgDetailPanel() {
      this.orgDetailPanelVisible = false
    },

    // 发送邮箱验证码并保存返回的code_token
    async sendInviteEmailCode() {
      const email = (this.orgDetail?.email || '').trim()
      if (!email) {
        this.$message.warning('未配置管理员邮箱，无法发送验证码')
        return
      }
      this.invite.sending = true
      try {
        const { codeToken } = await sendEmailCode(email)
        if (codeToken) this.invite.codeToken = codeToken
        this.$message.success('验证码已发送，请查收邮箱')
      } catch (e) {
        this.$message.error(`发送失败: ${e.message}`)
      } finally {
        this.invite.sending = false
      }
    },

    // 生成邀请码
    async generateInviteCode() {
      if (!this.orgDetail || !this.orgDetail.orgId) {
        this.$message.error('缺少机构上下文')
        return
      }
      this.invite.loading = true
      try {
        const headers = {}
        if (this.invite.codeToken) headers['code_token'] = this.invite.codeToken
        const res = await getOrgInvitationCode({ orgId: this.orgDetail.orgId }, headers)
        if (res && res.code === 1) {
          this.invite.code = res.data || ''
          if (this.invite.code) this.$message.success('邀请码已生成')
        } else {
          this.$message.error(`生成失败: ${res?.msg || '未知错误'}`)
        }
      } catch (e) {
        this.$message.error(`生成异常: ${e.message}`)
      } finally {
        this.invite.loading = false
      }
    },

    // 复制邀请码
    async copyInviteCode() {
      if (!this.invite.code) {
        this.$message.warning('暂无可复制的邀请码')
        return
      }
      try {
        await navigator.clipboard.writeText(this.invite.code)
        this.$message.success('已复制到剪贴板')
      } catch (e) {
        this.$message.warning('复制失败，请手动选择复制')
      }
    },

    // Batch import: open dialog
    openBatchImportDialog() {
      if (!this.orgDetail || !this.orgDetail.orgId) {
        this.$message.error('缺少机构上下文')
        return
      }
      this.batchImport.file = null
      this.batchImport.visible = true
    },

    // Handle file change
    handleBatchFileChange(file) {
      this.batchImport.file = file && file.raw ? file.raw : file
    },

    // Submit batch import
    async submitBatchImport() {
      if (!this.batchImport.file) {
        this.$message.warning('请先选择Excel文件')
        return
      }
      if (!this.orgDetail || !this.orgDetail.orgId) {
        this.$message.error('缺少机构上下文')
        return
      }
      this.batchImport.uploading = true
      try {
        const { batchAddUsersToOrg } = await import('@/api/org')
        await batchAddUsersToOrg({ file: this.batchImport.file, org_id: this.orgDetail.orgId })
        this.$message.success('批量导入成功')
        this.batchImport.visible = false
      } catch (e) {
        this.$message.error(`导入失败: ${e.message}`)
      } finally {
        this.batchImport.uploading = false
      }
    },

    // 加载机构树
    async loadOrgTree(orgId) {
      this.orgTreeLoading = true
      try {
        const res = await getOrgTree({ org_id: orgId })
        if (res && res.code === 1) {
          const raw = res.data || []
          // 归一化树节点，兼容多种后端字段
          const getChildren = (n) => {
            if (!n) return []
            // 常见字段名集合
            const candidateKeys = [
              'children', 'childList', 'child', 'childs', 'subList', 'subs', 'nodes'
            ]
            for (const key of candidateKeys) {
              const value = n[key]
              if (Array.isArray(value)) return value
            }
            return []
          }

          const normalize = (node) => {
            if (!node) return null
            const children = getChildren(node).map(normalize).filter(Boolean)
            return {
              id: node.orgId || node.id,
              label: node.orgName || node.name || '机构',
              orgType: node.orgType,
              orgLevel: typeof node.orgLevel === 'string' ? parseInt(node.orgLevel, 10) : node.orgLevel,
              status: node.status,
              children
            }
          }
          // 有些接口会返回 { list: [...] } 或 { tree: [...] }
          const containerArray = Array.isArray(raw)
            ? raw
            : (Array.isArray(raw.list) ? raw.list
              : (Array.isArray(raw.tree) ? raw.tree : [raw]))
          const treeArray = containerArray
          this.orgTree = treeArray.map(normalize).filter(Boolean)
        } else {
          this.orgTree = []
        }
      } catch (e) {
        this.orgTree = []
      } finally {
        this.orgTreeLoading = false
      }
    },

    // 从详情进入编辑（仅基础三项）
    editOrgFromDetail() {
      if (!this.orgDetail) return
      this.basicEditForm = {
        orgId: this.orgDetail.orgId,
        orgName: this.orgDetail.orgName || '',
        contactPhone: this.orgDetail.contactPhone || '',
        address: this.orgDetail.address || ''
      }
      this.orgDetailDialogVisible = false
      this.basicEditDialogVisible = true
    },

    // 保存基础信息
    saveBasicEdit() {
      if (!this.$refs.basicEditForm || !this.$refs.basicEditForm.validate) {
        return
      }
      this.$refs.basicEditForm.validate(async valid => {
        if (!valid) return
        try {
          const payload = {
            orgId: this.basicEditForm.orgId,
            orgName: this.basicEditForm.orgName,
            contactPhone: this.basicEditForm.contactPhone,
            address: this.basicEditForm.address
          }
          await updateOrg(payload)
          this.$message.success('机构基本信息已更新')
          this.basicEditDialogVisible = false
          // 刷新详情与列表
          await this.getOrgList()
          if (this.basicEditForm.orgId) {
            try {
              const res = await getOrgDetail({ org_id: this.basicEditForm.orgId })
              if (res && res.code === 1) this.orgDetail = res.data || this.orgDetail
            } catch (e) { /* ignore */ }
          }
        } catch (error) {
          this.$message.error(`更新失败: ${error.message}`)
        }
      })
    },

    // 添加用户到该机构
    async addUserIntoCurrentOrg() {
      if (!this.orgDetail || !this.orgDetail.orgId) {
        this.$message.error('当前无机构上下文')
        return
      }
      this.addUserLoading = true
      try {
        await addUserToOrg({ userId: (this.addUserForm.userId || '').trim(), orgId: this.orgDetail.orgId })
        this.$message.success('已为该机构添加用户')
        this.addUserForm.userId = ''
        this.addUserDialogVisible = false
      } catch (e) {
        this.$message.error(`添加失败: ${e.message}`)
      } finally {
        this.addUserLoading = false
      }
    },

    // 添加子机构：预填父级与层级并打开弹窗
    addChildOrg(parentRow) {
      if (!parentRow) return
      const parentLevel = parseInt(parentRow.orgLevel, 10) || 1
      const nextLevel = String(Math.min(3, parentLevel + 1))
      this.orgDialogTitle = '添加子机构'
      this.isAddingChild = true
      this.parentLevelForChild = parentLevel
      this.parentOrgTypeForChild = parentRow.orgType
      this.orgForm = {
        orgId: null,
        parentId: parentRow.orgId,
        orgName: '',
        orgType: parentRow.orgType,
        orgLevel: nextLevel,
        contactPhone: '',
        address: '',
        email: '',
        status: 1,
        sortOrder: 0
      }
      this.orgDialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.orgForm && this.$refs.orgForm.clearValidate) {
          this.$refs.orgForm.clearValidate()
        }
      })
    },

    // 返回上级机构
    goBackToParent() {
      if (this.searchForm.org_id) {
        // 如果有当前机构ID，需要找到其父级机构
        const currentOrg = this.orgList.find(org => org.orgId === this.searchForm.org_id)
        if (currentOrg && currentOrg.parentId) {
          this.searchForm.org_id = currentOrg.parentId
          this.searchForm.org_level = String(currentOrg.orgLevel - 1)
        } else {
          this.searchForm.org_id = ''
          this.searchForm.org_level = '1'
        }
      } else {
        this.searchForm.org_id = ''
        this.searchForm.org_level = '1'
      }
      this.getOrgList()
    }
  }
}
